package com.education.platform.api.service.impl;

import com.alibaba.fastjson.JSON;
import com.education.platform.api.config.ThreadUser;
import com.education.platform.api.service.UserBaseService;
import com.education.platform.api.vo.request.UserBaseUpdateVO;
import com.education.platform.common.enums.FlowTypeEnum;
import com.education.platform.common.enums.PointsTypeEnum;
import com.education.platform.common.exception.BusinessException;
import com.education.platform.common.redis.RedisUtils;
import com.education.platform.common.service.impl.BaseServiceImpl;
import com.education.platform.common.util.BeanUtil;
import com.education.platform.common.util.ShareCodeUtil;
import com.education.platform.common.util.StringUtils;
import com.education.platform.dao.CourseCommentDao;
import com.education.platform.dao.PointsFlowDao;
import com.education.platform.dao.UserBaseDao;
import com.education.platform.dao.UserPointsDao;
import com.education.platform.dao.entity.CourseCommentDO;
import com.education.platform.dao.entity.PointsFlowDO;
import com.education.platform.dao.entity.UserBaseDO;
import com.education.platform.dao.entity.UserPointsDO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
* describe: 前端用户基础表
* @author : tomato
* @date: 2020-06-07 11:38:44.106
**/
@Service
public class UserBaseServiceImpl extends BaseServiceImpl<UserBaseDao, UserBaseDO> implements UserBaseService {

	private static final Logger LOGGER = LoggerFactory.getLogger(UserBaseServiceImpl.class);

    @Autowired
	private UserBaseDao userBaseDao;

    @Autowired
    private RedisUtils redisUtils;
    @Value("${token.expire}")
    private int tokenExpire;

    @Autowired
    private CourseCommentDao courseCommentDao;
    @Autowired
    private UserPointsDao userPointsDao;
    @Autowired
    private PointsFlowDao pointsFlowDao;

    private static final float REBATE_POINT=10;

    /**
     * 编辑个人信息
     *
     * @param update
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void editInformation(UserBaseUpdateVO update) {
        UserBaseDO updateUser  = BeanUtil.convert(update,UserBaseDO.class);
        updateUser.setId(ThreadUser.getUserId());
        updateUser.setUpdateTime(new Date());
        userBaseDao.updateById(updateUser);

        UserBaseDO userBaseDO = ThreadUser.getUser(UserBaseDO.class);

        if(StringUtils.isNotEmpty(update.getPhoto())){
            userBaseDO.setPhoto(update.getPhoto());
        }
        if(StringUtils.isNotEmpty(update.getNickName())){
            userBaseDO.setNickName(update.getNickName());
        }
        if(Boolean.TRUE.equals(update.getGuide())){
            userBaseDO.setGuide(update.getGuide());
        }
        redisUtils.setString(ThreadUser.getUserTokenRedisKey(), tokenExpire,JSON.toJSONString(userBaseDO));
        if(StringUtils.isNotEmpty(update.getPhoto())||StringUtils.isNotEmpty(update.getNickName())){
            this.updateCommentMsg(ThreadUser.getUserId(),update.getNickName(),update.getPhoto());
        }
    }

    /**
     * 修改已评论的用户信息
     * @param userId
     * @param nickName
     * @param cover
     */
    private void updateCommentMsg(Integer userId,String nickName,String cover){
        CourseCommentDO updateComment = new CourseCommentDO();
        updateComment.setUserId(userId);
        updateComment.setUserName(nickName);
        updateComment.setUserCover(cover);
        courseCommentDao.updateCommentUserByUserId(updateComment);

    }

    /**
     * 提交邀请码
     *
     * @param code
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void commitInviteCode(String code) {
        if(StringUtils.isEmpty(code)){
            throw new BusinessException("邀请码必填");
        }
        int inviteUserId =  ShareCodeUtil.shareCode2id(code);
        if(inviteUserId == 0){
            throw new BusinessException("邀请码错误！");
        }
        if(ThreadUser.getUserId().equals(inviteUserId)){
            throw new BusinessException("邀请码错误！");
        }
       UserBaseDO inviteUser =  userBaseDao.getById(inviteUserId);
       if(inviteUser == null || !code.equals(inviteUser.getCode())){
           throw new BusinessException("邀请码错误！");
       }
        UserBaseDO currentUser =   userBaseDao.getById(ThreadUser.getUserId());
       if(currentUser.getInviter()!=null){
           throw new BusinessException("已填写过邀请码！");
       }
       //保存邀请人id
        UserBaseDO updateUser = new UserBaseDO();
        updateUser.setId(currentUser.getId());
        updateUser.setInviter(inviteUserId);
        userBaseDao.updateById(updateUser);
       //邀请人  + 1积分， 当前用户第一次充值，邀请人需要+1历史豆。
       this.inviteUserAddPoint(inviteUserId);
    }

    /**
     *  邀请人增加积分   1
     * @param inviteUserId
     */
    private void inviteUserAddPoint(Integer inviteUserId){
        UserPointsDO query = new UserPointsDO();
        query.setUserId(inviteUserId);
        UserPointsDO inviteUserPoint = userPointsDao.get(query);
        userPointsDao.addPoints(REBATE_POINT,inviteUserId);
        PointsFlowDO pointsFlowDO  = new PointsFlowDO();
        pointsFlowDO.setUserId(inviteUserId);
        pointsFlowDO.setFlowNumber(REBATE_POINT);
        pointsFlowDO.setBeforeNumber(inviteUserPoint.getPoints());
        pointsFlowDO.setAfterNumber(inviteUserPoint.getPoints() +REBATE_POINT);
        pointsFlowDO.setFlowType(FlowTypeEnum.IN.getValue());
        pointsFlowDO.setBusinessType(PointsTypeEnum.INVITE_USER.getValue());
        pointsFlowDO.setRemarks(PointsTypeEnum.INVITE_USER.getDes());
        pointsFlowDO.setDeleted(false);
        pointsFlowDO.setCreateTime(new Date());
        pointsFlowDao.insert(pointsFlowDO);
    }

    /**
     * 修改版本
     *
     * @param
     * @param
     */
    @Override
    public void updateVersion(UserBaseDO userBaseDO) {
        userBaseDao.updateVersion(userBaseDO);
    }
}
